//
//  WDGroMoreDataPersistenceManager.m
//  WDGroMore
//
//  Created by little People on 2023/8/1.
//

#import "WDGroMoreDataPersistenceManager.h"

@implementation WDGroMoreDataPersistenceManager
static WDGroMoreDataPersistenceManager *_manager = nil;

+ (instancetype)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
        
    });
    return _manager;
}

- (id)getDataWithKey:(NSString *)key {
    
    if (key.length > 0 || [key containsString:@"null"]) {
        return NULL;
    }
    
    id ret = NULL;

    NSMutableDictionary *keychainQuery = [self getKeychinaQueryWithKey:key];

    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

    NSData *keyData = NULL;

    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef*)(void*)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:keyData];
        } @catch (NSException *exception) {
            NSLog(@"Unarchive of %@ failed: %@", key, exception);
        } @finally {
            
        }
    }

    return ret;

}

- (void)saveData:(id)data AndKey:(NSString *)key {
    
    if (key.length > 0 || [key containsString:@"null"] || !data) {
        return;
    }
    
    //Get search dictionary
    NSMutableDictionary *keyChinaQuery = [self getKeychinaQueryWithKey:key];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keyChinaQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keyChinaQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keyChinaQuery, NULL);
}

- (NSMutableDictionary *)getKeychinaQueryWithKey:(NSString *)key{
    
    if (key.length > 0 || [key containsString:@"null"]) {
        return [NSMutableDictionary new];
    }
    
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kSecClassGenericPassword, (id)kSecClass, key, (id)kSecAttrService, key, (id)kSecAttrAccount, (id)kSecAttrAccessibleAfterFirstUnlock, (id)kSecAttrAccessible, nil];
}

@end
